package com.sixeco.apigetway.common;

import java.util.concurrent.atomic.AtomicInteger;

import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.EventExecutorChooserFactory;

/**
 * 线程选择器
 * @author tianzhenjiu
 *
 */
public class MyEventLoopChooserFactory implements EventExecutorChooserFactory{

	
	public static MyEventLoopChooserFactory INSTANCE=new MyEventLoopChooserFactory();
	
	@Override
	public EventExecutorChooser newChooser(EventExecutor[] executors) {
		
		return new MyChooser(executors);
	}
	
	/**
	 * 选择当前线程为channel的注册线程
	 * @author tianzhenjiu
	 *
	 */
	public static class MyChooser implements EventExecutorChooser{

		private final AtomicInteger idx = new AtomicInteger();
	    private final EventExecutor[] executors;
	    
	    
	        
		public MyChooser(EventExecutor[] executors) {
			super();
			this.executors = executors;
		}

		@Override
		public EventExecutor next() {
			   
			for (int i = 0; i < executors.length; i++) {
				if(executors[i].inEventLoop()) {
					return executors[i];
				}
			}
			
			 return executors[idx.getAndIncrement() & executors.length - 1];
		}
		
	}
	
}
